#!/bin/bash

runCommand()
{
    if [ "$1" == "mpirun" ]; then sol="$4"; else sol="$1"; fi
    sol=$(basename -- "$sol")
    sol="${sol%.*}"
    if [ -f log."$sol" ]; then rm log."$sol"; fi
    "$@" 1> >(tee -a log."$sol") 2> >(tee -a log."$sol" >&2)
    err=$?
    if [ ! $err -eq 0 ]; then exit $err; fi
}

%{%(system/FoamRuntime%)
%:BlueCFD
%:default
# Unset and source bashrc
FOAMDIR="%(system/TranslatedFoamPath%)"
source "$FOAMDIR/etc/config.sh/unset" 2> /dev/null
source "$FOAMDIR/etc/bashrc"

%}
# Copy mesh from mesh case dir if available
MESHDIR="%(meshDir%)"
if [ -f "$MESHDIR"/constant/polyMesh/faces ]
then
    rm -r constant/polyMesh 2> /dev/null
    cp -r "$MESHDIR"/constant/polyMesh constant/polyMesh
elif [ ! -f constant/polyMesh/faces ]
then
    echo "Fatal error: Unable to find mesh in directory $MESHDIR" 1>&2
    exit 1
fi

# Update patch name and type
runCommand createPatch -overwrite

%{%(zonesPresent%)
%:True
# Scaling .stl files exported from FreeCAD from mm to m
%{%(zones%)
%{%(zones/%(0%)/PartNameList%)
runCommand surfaceTransformPoints -scale "(0.001 0.001 0.001)" "constant/triSurface/%(0%).stl" "constant/triSurface/%(0%)Scaled.stl"

%}
%}
# Set cell zones contained inside the .stl surfaces
runCommand topoSet -dict system/topoSetZonesDict

%}
%{%(initialisationZonesPresent%)
%:True
# Set internal fields according to setFieldsDict
runCommand setFields

%}
%{%(bafflesPresent%)
%:True
%{%(createPatchesFromSnappyBaffles%)
%:False
# Combine mesh faceZones
runCommand topoSet -dict system/topoSetBafflesDict

# Creating baffles
runCommand createBaffles -overwrite

%}
%}
%{%(runChangeDictionary%)
%:True
# Update patch name and type
runCommand changeDictionary

%}
%{%(initialValues/PotentialFoam%)
%:True
# Initialise flow
%{%(bafflesPresent%)
%:True
# Baffle BC does not work with potentialFoam; do not initialise p
runCommand potentialFoam -initialiseUBCs
%:default
runCommand potentialFoam -initialiseUBCs -writep
%}

%}
%{%(solver/Parallel%)
%:True
# Run application in parallel
runCommand decomposePar -force
runCommand mpirun -n %(solver/ParallelCores%) %(solver/SolverName%) -parallel
%:False
# Run application
runCommand %(solver/SolverName%)
%}

